package middleware

import (
	jwt "github.com/golangblogs/gojwt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"strconv"
	"zg2_zy/zy6_company/api/internal/types"
)

type UserLoginMiddleware struct {
}

func NewUserLoginMiddleware() *UserLoginMiddleware {
	return &UserLoginMiddleware{}
}

func (m *UserLoginMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		token := r.Header.Get("token")
		if token == "" {
			resp := types.Response{
				Message: "token is nil",
				Code:    1001,
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}

		newJwt := jwt.NewJWT("Token")
		claims, err := newJwt.ParseToken(token)

		if err != nil {
			resp := types.Response{
				Message: "token is invalid",
				Code:    1001,
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}

		userId := claims.ID
		r.ParseForm()
		r.Form.Set("user_id", strconv.Itoa(int(userId)))
		// Passthrough to next handler if need
		next(w, r)
	}
}
